/*
 * Copyright (c) 2009-2013 EvTech Project
 * All rights reserved.
 * 
 * This file is part of Game packet.
 *
 * Game packet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 *
 * Game packet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Game packet.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package fi.honkalampisaatio.game.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class SettingsWriter {

	public static SettingsWriter INSTANCE;
	
	public static SettingsWriter getInstance() {
		if(INSTANCE==null) {
			INSTANCE = new SettingsWriter();
		}
		return INSTANCE;
	}

	
	public void writeGameSettings(String filename, Object settings) 
			throws JAXBException, IOException, NullPointerException {
		File file = new File(filename);
		File folder = new File(filename.substring(0, filename.lastIndexOf("/")));
		if(!folder.exists())
		{
			folder.mkdirs();
		}
		if(file.exists())
		{
			file.delete();
		}
		JAXBContext context = JAXBContext.newInstance(settings.getClass());
		Marshaller m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		m.marshal(settings, new FileOutputStream(filename));
	}
}
